package cn.edu.nju.software.zp13.assignment5.servlet;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.soap.SOAPMessage;

import cn.edu.nju.software.zp13.assignment5.service.CourseScoreManager;
import cn.edu.nju.software.zp13.assignment5.service.soapMessage.CourseScoreListSOAPMsgProducer;
import cn.edu.nju.software.zp13.assignment5.service.soapMessage.IllegalQueryConditionSOAPMsgProducer;
import cn.edu.nju.software.zp13.assignment5.service.soapMessage.SOAPMsgProducer;
import cn.edu.nju.software.zp13.assignment5.service.soapMessage.SOAPMsgWriter;
import cn.edu.nju.software.zp13.client.assignment4.sax.xmlNodeEntity.CourseScoreList;

/**
 * Servlet implementation class ScoreQuery
 */
@WebServlet("/scoreQuery")
public class ScoreQuery extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private CourseScoreManager csbl;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ScoreQuery() {
		super();
		csbl = new CourseScoreManager();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		ProducerFactory pf = new ProducerFactory();
		SOAPMsgProducer producer = pf.newSOAPMsgProducer(request);
		SOAPMessage msg = producer.produceSOAPMessage();
		SOAPMsgWriter.writeMsg(msg, response.getOutputStream());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

	private class ProducerFactory {
		public SOAPMsgProducer newSOAPMsgProducer(HttpServletRequest request) {
			SOAPMsgProducer producer = null;
			Map<String, String[]> paras = request.getParameterMap();
			if (paras.keySet().size() != 1) {
				producer = new IllegalQueryConditionSOAPMsgProducer();
			} else {
				String[] keys = paras.keySet().toArray(new String[1]);
				if ("studentId".equals(keys[0])) {
					String studentId = request.getParameter("studentId");
					CourseScoreList csl = csbl.getCourseScore(studentId);
					producer = new CourseScoreListSOAPMsgProducer(csl);
				} else {
					producer = new IllegalQueryConditionSOAPMsgProducer();
				}
			}
			return producer;
		}
	}
}
